"""
Case Type   : 问题回归
Case Name   : 执行drop operator
Create At   : 2023/02/17
Owner       : cr13
Description :
    1.创建函数
    2.创建操作符
    3.删除操作符
    4.清理环境
Expect      :
    1.成功
    2.成功
    3.成功
    4.成功
History     :
"""

import os
import unittest
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class BugFix(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.constant = Constant()
        self.com = Common()
        self.commsh = CommonSH('PrimaryDbUser')
        self.function = 'f_bug_fix_049'
        self.support_extended_features = self.com.show_param(
            'support_extended_features')
        guc_res = self.commsh.execute_gsguc(
            'set', self.constant.GSGUC_SUCCESS_MSG,
            'support_extended_features=on')
        self.assertTrue(guc_res, '执行失败')
        result = self.commsh.restart_db_cluster()
        self.assertTrue(result, '执行失败')

    def test_bug_fix(self):
        text = "----step1:创建函数 expect:成功----"
        self.log.info(text)
        sql_cmd = f"create or replace function {self.function}(int,int) " \
            f"returns int as " \
            f"\$\$ " \
            f"begin" \
            f"  return (\$1-\$2)*10;" \
            f"end;" \
            f"\$\$ language plpgsql;"
        result = self.commsh.execut_db_sql(sql_cmd)
        self.log.info(result)
        self.assertIn(self.constant.CREATE_FUNCTION_SUCCESS_MSG, result,
                      '执行失败' + text)

        text = "----step2:创建操作符 expect:成功----"
        self.log.info(text)
        sql_cmd = f"create operator #* (" \
            f"procedure={self.function},leftarg=int,rightarg=int);"
        result = self.commsh.execut_db_sql(sql_cmd)
        self.log.info(result)
        self.assertIn('CREATE OPERATOR', result, '执行失败' + text)

        text = "----step3:删除操作符 expect:成功----"
        self.log.info(text)
        sql_cmd = f"drop operator #* (int,int);"
        result = self.commsh.execut_db_sql(sql_cmd)
        self.log.info(result)
        self.assertIn('DROP OPERATOR', result, '执行失败' + text)

    def tearDown(self):
        text = '-----step4:清理环境 expect:成功-----'
        self.log.info(text)
        sql_cmd = f"drop function {self.function};"
        result = self.commsh.execut_db_sql(sql_cmd)
        self.log.info(result)
        guc_res = self.commsh.execute_gsguc(
            'set', self.constant.GSGUC_SUCCESS_MSG,
            f'support_extended_features={self.support_extended_features}')
        result1 = self.commsh.restart_db_cluster()
        self.assertTrue(result1, '执行失败' + text)
        self.assertTrue(guc_res, '执行失败' + text)
        self.assertIn(self.constant.DROP_FUNCTION_SUCCESS_MSG, result,
                      '执行失败' + text)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
